//
//  Login_Vc.swift
//  MikerShop
//
//  Created by eme on 2016/11/8.
//  Copyright © 2016年 eme. All rights reserved.
//

/*
 owner:cy
 update:2016年10月26日09:08:10
 info: 登陆界面
 model: UserModel
 viewmodel: LoginViewModel
 */
import RxSwift
import NetWorkCore
import SwiftyUserDefaults
import UtilCore
import ModelProtocol
import RickonCore
import BrandonCore

class Login_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var login_Btn: UIButton!
    @IBOutlet weak var username_Tf: UITextField!
    @IBOutlet weak var username_Border_V: UIView!
    @IBOutlet weak var password_Tf: UITextField!
    @IBOutlet weak var password_Border_V: UIView!
    
    @IBOutlet weak var register_Btn: UIButton!
    
    @IBOutlet weak var forget_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var manageVm :Login_Vm?
    
    /// 表示是否是modal出来的 如果是的话导航栏需要显示关闭按钮 否则不显示
    var isModal:Bool = false
    
    private lazy var secureBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 35, height: 45)
        button.setTitle("", for: .normal)
        
        button.setImage(UIImage(named: "selected_secure_textfield_btn", in: JonSnowCore.bundle, compatibleWith: nil), for: .selected)
        button.setImage(UIImage(named: "unselected_secure_textfield_btn", in: JonSnowCore.bundle, compatibleWith: nil), for: .normal)
        return button
    }()
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UtilCore.sharedInstance.isHasToLoginVc = true
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        /*
         在这块需要 将isHasToLoginVc 改为false ，以防当出现‘201003请登录后再操作’的时候 可以跳转到登陆界面
         */
        UtilCore.sharedInstance.isHasToLoginVc = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        self.customLeftBarButtonItem()
        self.password_Tf.rightView = self.secureBtn
        self.password_Tf.rightViewMode = .whileEditing
        self.secureBtn.isSelected = self.password_Tf.isSecureTextEntry
        self.secureBtn.rx.tap.subscribe(onNext: { [unowned self] ( _ ) in
            self.secureBtn.isSelected = !self.secureBtn.isSelected
            self.password_Tf.isSecureTextEntry = self.secureBtn.isSelected
        }).disposed(by: disposeBag)
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.title = "\(AppConfig.appTitle)登录"
        self.login_Btn.changeBorderColor(UIColor.clear, cornerRadius: 3.5)
        self.login_Btn.backgroundColor = UIColor.clear
        self.login_Btn.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.btn.disabled)
        self.username_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.password_Border_V.changeBorderColor(Theme.tf.border, cornerRadius: 2.0,borderWidth:0.5 )
        self.username_Tf.changePlaceholder("请输入手机号或者商户ID",placeColor:Theme.tf.placeorder,textColor:Theme.tf.text)
        self.password_Tf.changePlaceholder("登录密码",placeColor:Theme.tf.placeorder,textColor: Theme.tf.text)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = Login_Vm(input: (
            username: username_Tf.rx.text.orEmpty.asObservable(),
            password: password_Tf.rx.text.orEmpty.asObservable(),
            loginTaps: login_Btn.rx.tap.asObservable()
            ), validationService: LoginValidationService())
        
        self.manageVm?.signupEnabled
            .subscribe(onNext: {  [unowned self](valid) in
                self.login_Btn.isEnabled = valid
                self.login_Btn.alpha = valid ? 1.0 : 0.3
            }).addDisposableTo(disposeBag)
        
        self.manageVm?.signedIn
            .do{ _ in
                self.view.endEditing(true)
            }
            .subscribe(onNext: { [unowned self] (result) in
                switch result {
                /// 这块需要判断 是否审核成功了
                case.success(let userModel):
                    self.loginSuccess(model: userModel)
                case.failure(let error):
                    self.view.toastError(error)
                }
            }).addDisposableTo(disposeBag)
        self.manageVm?.signingIn.bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.register_Btn.rx.tap.subscribe(onNext: { ( _ ) in
            _ = "register".openURL()
        }).disposed(by: disposeBag)
        self.forget_Btn.rx.tap.subscribe(onNext: { ( _ ) in
            _ = "forget".openURL()
        }).disposed(by: disposeBag)
    }
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        if self.isModal {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(image:  UIImage(named: "login-close", in: JonSnowCore.bundle, compatibleWith: nil), style: .plain, target: self, action: #selector(closeVc))
        }
    }
    /// 这块需要判断
    /*
     跳转到登陆界面有
     1.第一次打开app 从引导页跳转到登陆界面   --- 不显示关闭按钮
     2. user对象为空或者 hasLogined为false即没有跳转到过首页 虽然已经登陆过但是需要重新登陆 --- 不显示关闭按钮
     3. 后台返回需要重新登陆  --- 这块是model出来 则需要显示关闭按钮
     */
    func loginSuccess(model:UserModel) -> Void {
        /// 登陆成功后 点击了进入觅客商城按钮 则设置为true 否则为false
        //        let  hasLogined = Defaults[.hasLogined]
        ///更新本地用户信息
        AppData.updateUserModel(model)
        ///  这块需要直接跳转到首页
        self.closeVc()
        //        //1通过 2表示未通过
        //        if model.thrState == "1" && hasLogined{
        //            /*
        //             1.这块需要判断下 是否modal出来的isModal ， 如果isModal 为true 则直接调用closeVc()即可 否则需要跳转到 首页
        //             */
        //            if self.isModal {
        //                NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConfig.notification.reloginSuccessKey), object: model)
        //                self.closeVc()
        //            }else{
        //                ///  这块需要直接跳转到首页
        //                _ = "loginsuccess".openURL()
        //            }
        //        }else{
        //            /// 跳转到审核详情界面 审核失败或其它
        //            _ = "reviewdetails".openURL(["spid":model.thrid])
        //        }
    }
    func closeVc() -> Void {
        self.dismiss(animated: true, completion: nil)
    }
}


